package com.yuandengta.yomall.cart.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.constant.CartConstant;
import com.yuandengta.common.utils.JsonUtils;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.cart.feign.ProductFeignService;
import com.yuandengta.yomall.cart.interceptor.CartInterceptor;
import com.yuandengta.yomall.cart.service.CartService;
import com.yuandengta.yomall.cart.vo.CartItemVO;
import com.yuandengta.yomall.cart.vo.CartVO;
import com.yuandengta.yomall.cart.vo.SkuInfoVO;
import com.yuandengta.yomall.cart.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 购物车服务 {@link CartServiceImpl}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItemVO addToCart(Long skuId, Integer num) throws Exception {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String)cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(res)) {
            // 购物车有此商品，修改数量
            CartItemVO cartItemVO = JsonUtils.jsonToPojo(res, CartItemVO.class);
            cartItemVO.setCount(cartItemVO.getCount() + num);

            // 购物项存放到 Redis
            String json = JsonUtils.objectToJson(cartItemVO);
            cartOps.put(skuId.toString(), json);

            return cartItemVO;
        } else {
            // 购物车没有此商品，新增商品到购物车
            CartItemVO cartItemVO = new CartItemVO();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1.远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVO skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                    });
                    // 添加商品到购物车
                    cartItemVO.setCheck(true);
                    cartItemVO.setCount(num);
                    cartItemVO.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVO.setTitle(skuInfo.getSkuTitle());
                    cartItemVO.setSkuId(skuId);
                    cartItemVO.setPrice(skuInfo.getPrice());
                } else {
                    log.error("调用远程服务 yomall-product 查询商品详细信息失败");
                }
            }, executor);

            CompletableFuture<Void> getSKuAttrValuesTask = CompletableFuture.runAsync(() -> {
                // 2.远程查询sku销售属性
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVO.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSKuAttrValuesTask).get();

            // 购物项存放到 Redis
            String json = JsonUtils.objectToJson(cartItemVO);
            cartOps.put(skuId.toString(), json);

            return cartItemVO;
        }
    }

    /**
     * 获取购物车中某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItemVO getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItemVO cartItemVO = JsonUtils.jsonToPojo(res, CartItemVO.class);
        return cartItemVO;
    }

    /**
     * 获取购物车
     * @return
     */
    @Override
    public CartVO getCart() throws Exception {
        CartVO cartVO = new CartVO();
        UserVO user = CartInterceptor.threadLocal.get();
        if (user.getUserId() != null) {
            // 登录
            String cartKey = CartConstant.CART_PREFIX + user.getUserId();
            // 如果临时购物车的数据还没有合并
            String tempCartKey = CartConstant.CART_PREFIX + user.getUserKey();
            List<CartItemVO> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null && tempCartItems.size() > 0) {
                // 临时购物车有数据，需要合并
                for (CartItemVO cartItem : tempCartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 清除临时购物车数据
                clearCart(tempCartKey);
            }
            // 获取登录后的购物车数据，包含合并过来的临时购物车数据和登录后的购物车的数据
            List<CartItemVO> cartItems = getCartItems(cartKey);
            cartVO.setItems(cartItems);
        } else {
            // 未登录
            String cartKey = CartConstant.CART_PREFIX + user.getUserKey();
            // 获取临时购物车的所有购物项
            List<CartItemVO> cartItems = getCartItems(cartKey);
            cartVO.setItems(cartItems);
        }

        return cartVO;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
       redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param isChecked
     */
    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        CartItemVO cartItem = getCartItem(skuId);
        cartItem.setCheck(isChecked == 1 ? true : false);
        // 购物项存放到 Redis
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String json = JsonUtils.objectToJson(cartItem);
        cartOps.put(skuId.toString(), json);
    }

    /**
     * 修改购物项商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVO cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        // 购物项存放到 Redis
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String json = JsonUtils.objectToJson(cartItem);
        cartOps.put(skuId.toString(), json);
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取用户的所有购物项
     * @return
     */
    @Override
    public List<CartItemVO> getUserCartItems() {
        UserVO loginUser = CartInterceptor.threadLocal.get();
        if (loginUser == null) {
            return null;
        }

        String cartKey = CartConstant.CART_PREFIX + loginUser.getUserId();
        List<CartItemVO> vos = getCartItems(cartKey).stream()
                .filter(item -> item.getCheck())
                .map(item -> {
                    // 调用远程服务查询商品最新价格
                    R r = productFeignService.getPrice(item.getSkuId());
                    if (r.getCode() == 0) {
                        BigDecimal price = r.getData("price", new TypeReference<BigDecimal>() {
                        });
                        // 更新商品最新价格
                        item.setPrice(price);
                    } else {
                        log.error("调用远程服务 yomall-product 查询商品价格失败");
                    }

                    return item;
                })
                .collect(Collectors.toList());

        return vos;
    }

    /**
     * 获取购物车中所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItemVO> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVO> itemVOS = values.stream().map(obj -> {
                String res = (String) obj;
                CartItemVO cartItemVO = JsonUtils.jsonToPojo(res, CartItemVO.class);
                return cartItemVO;
            }).collect(Collectors.toList());
            return itemVOS;
        }
        return null;
    }

    /**
     * 获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 从 threadlocal 中获取当前用户
        UserVO user = CartInterceptor.threadLocal.get();
        String cartKey = "";

        if (user.getUserId() != null) {
            // 登录用户
            cartKey = CartConstant.CART_PREFIX + user.getUserId();
        } else {
            // 访客
            cartKey = CartConstant.CART_PREFIX + user.getUserKey();
        }

        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);

        return ops;
    }


}
